#include <iostream>
#include <sys/socket.h> // socket
#include <netinet/in.h> // local
#include <arpa/inet.h> // htons inet_addr
#include <cstring> // memset 
#include <unistd.h> // close

int main(int argc, char *argv[])
{
    if (argc != 3) 
    {
        std::cout << "Usage: ./TcpClient serverip serverport" << std::endl;
        return 1;
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socket fail" << std::endl;
        return 1;
    }

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    int n = connect(sockfd, (struct sockaddr*)&server, sizeof(server));
    if (n < 0)
    {
        std::cout << "connect fail" << std::endl;
        close(sockfd);
        return 1;
    }

    std::cout << "Connected to server at " << serverip << ":" << serverport << std::endl;

    while (true)
    {
        std::string inbuffer;
        std::cout << "Please Enter# ";
        std::getline(std::cin, inbuffer);
        int n = write(sockfd, inbuffer.c_str(), inbuffer.size());
        if (n > 0)
        {
            char buffer[1024];
            int m = read(sockfd, buffer, sizeof(buffer) - 1);
            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << buffer << std::endl;
            }
            else
            {
                std::cout << "read fail" << std::endl;
                break;
            }
        }
        else
        {
            std::cout << "write fail" << std::endl;
            break;
        }
    }

    close(sockfd);

    return 0;
}